home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Language/OS - Multiplatform Resource Library
/
LANGUAGE OS.iso
/
python
/
pythnlbn.lha
/
python-lib.info-2
(
.txt
)
< prev
next >
Wrap
GNU Info File
|
1993-07-29
|
50KB
|
926 lines
This is Info file python-lib.info, produced by Makeinfo-1.43 from the
input file @out.texi.
This file describes the built-in types, exceptions and functions and
the standard modules that come with the Python system. It assumes
basic knowledge about the Python language. For an informal
introduction to the language, see the Python Tutorial. The Python
Reference Manual gives a more formal definition of the language.
(These manuals are not yet available in INFO or Texinfo format.)
Copyright (C) 1991, 1992, 1993 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
File: python-lib.info, Node: math, Next: time, Prev: __main__, Up: Built-in Modules
Built-in Module `math'
======================
This module is always available. It provides access to the
mathematical functions defined by the C standard. They are:
-- function of module math: acos (X)
-- function of module math: asin (X)
-- function of module math: atan (X)
-- function of module math: atan2 (X, Y)
-- function of module math: ceil (X)
-- function of module math: cos (X)
-- function of module math: cosh (X)
-- function of module math: exp (X)
-- function of module math: fabs (X)
-- function of module math: floor (X)
-- function of module math: fmod (X, Y)
-- function of module math: frexp (X)
-- function of module math: ldexp (X, Y)
-- function of module math: log (X)
-- function of module math: log10 (X)
-- function of module math: modf (X)
-- function of module math: pow (X, Y)
-- function of module math: sin (X)
-- function of module math: sinh (X)
-- function of module math: sqrt (X)
-- function of module math: tan (X)
-- function of module math: tanh (X)
Note that `frexp' and `modf' have a different call/return pattern than
their C equivalents: they take a single argument and return a pair of
values, rather than returning their second return value through an
`output parameter' (there is no such thing in Python).
The module also defines two mathematical constants:
-- data of module math: pi
-- data of module math: e
File: python-lib.info, Node: time, Next: regex, Prev: math, Up: Built-in Modules
Built-in Module `time'
======================
This module provides various time-related functions. It is always
available. (On some systems, not all functions may exist; e.g. the
"milli" variants can't always be implemented.)
An explanation of some terminology and conventions is in order.
* The "epoch" is the point where the time starts. On January 1st
that year, at 0 hours, the "time since the epoch" is zero.
* UTC is Coordinated Universal Time (formerly known as Greenwich
Mean Time). The acronym UTC is not a mistake but a compromise
between English and French.
* DST is Daylight Saving Time, an adjustment of the timezone by
(usually) one hour during part of the year. DST rules are magic
(determined by local law) and can change from year to year. The C
library has a table containing the local rules (often it is read
from a system file for flexibility) and is the only source of
True Wisdom in this respect.
* The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is
expressed. E.g. on most UNIX systems, the clock "ticks" only
every 1/50th or 1/100th of a second, and on the Mac, it ticks 60
times a second.
Functions and data items are:
-- data of module time: altzone
The offset of the local DST timezone, in seconds west of the 0th
meridian, if one is defined. Only use this if `daylight' is
nonzero.
-- data of module time: daylight
Nonzero if a DST timezone is defined.
-- function of module time: gmtime (SECS)
Convert a time expressed in seconds since the epoch to a tuple of
9 integers, in UTC: year (e.g. 1993), month (1-12), day (1-31),
hour (0-23), minute (0-59), second (0-59), weekday (0-6, monday
is 0), julian day (1-366), dst flag (always zero). Fractions of
a second are ignored. Note subtle differences with the C
function of this name.
-- function of module time: localtime (SECS)
Like `gmtime' but converts to local time. The dst flag is set to
1 when DST applies to the given time.
-- function of module time: millisleep (MSECS)
Suspend execution for the given number of milliseconds.
(Obsolete, you can now use use `sleep' with a floating point
argument.)
-- function of module time: millitimer ()
Return the number of milliseconds of real time elapsed since some
point in the past that is fixed per execution of the python
interpreter (but may change in each following run). The return
value may be negative, and it may wrap around.
-- function of module time: mktime (TUPLE)
This is the inverse function of `localtime'. Its argument is the
full 9-tuple (since the dst flag is needed). It returns an
integer.
-- function of module time: sleep (SECS)
Suspend execution for the given number of seconds. The argument
may be a floating point number to indicate a more precise sleep
time.
-- function of module time: time ()
Return the time as a floating point number expressed in seconds
since the epoch, in UTC. Note that even though the time is
always returned as a floating point number, not all systems
provide time with a better precision than 1 second. An
alternative for measuring precise intervals is `millitimer'.
-- data of module time: timezone
The offset of the local (non-DST) timezone, in seconds west of
the 0th meridian (i.e. negative in most of Western Europe,
positive in the US, zero in the UK).
-- data of module time: tzname
A tuple of two strings: the first is the name of the local non-DST
timezone, the second is the name of the local DST timezone. If
no DST timezone is defined, the second string should not be used.
File: python-lib.info, Node: regex, Next: marshal, Prev: time, Up: Built-in Modules
Built-in Module `regex'
=======================
This module provides regular expression matching operations similar to
those found in Emacs. It is always available.
By default the patterns are Emacs-style regular expressions; there is
a way to change the syntax to match that of several well-known UNIX
utilities.
This module is 8-bit clean: both patterns and strings may contain null
bytes and characters whose high bit is set.
*Please note:* There is a little-known fact about Python string
literals which means that you don't usually have to worry about
doubling backslashes, even though they are used to escape special
characters in string literals as well as in regular expressions. This
is because Python doesn't remove backslashes from string literals if
they are followed by an unrecognized escape character. *However*, if
you want to include a literal "backslash" in a regular expression
represented as a string literal, you have to *quadruple* it. E.g. to
extract LaTeX `\section{...}' headers from a document, you can use
this pattern: `'\\\\section{\(.*\)}''.
The module defines these functions, and an exception:
-- function of module regex: match (PATTERN, STRING)
Return how many characters at the beginning of STRING match the
regular expression PATTERN. Return `-1' if the string does not
match the pattern (this is different from a zero-length match!).
-- function of module regex: search (PATTERN, STRING)
Return the first position in STRING that matches the regular
expression PATTERN. Return -1 if no position in the string
matches the pattern (this is different from a zero-length match
anywhere!).
-- function of module regex: compile (PATTERN, TRANSLATE)
Compile a regular expression pattern into a regular expression
object, which can be used for matching using its `match' and
`search' methods, described below. The optional TRANSLATE, if
present, must be a 256-character string indicating how characters
(both of the pattern and of the strings to be matched) are
translated before comparing them; the `i'-th element of the
string gives the translation for the character with ASCII code
`i'.
The sequence
prog = regex.compile(pat)
result = prog.match(str)
is equivalent to
result = regex.match(pat, str)
but the version using `compile()' is more efficient when multiple
regular expressions are used concurrently in a single program.
(The compiled version of the last pattern passed to
`regex.match()' or `regex.search()' is cached, so programs that
use only a single regular expression at a time needn't worry
about compiling regular expressions.)
-- function of module regex: set_syntax (FLAGS)
Set the syntax to be used by future calls to `compile', `match'
and `search'. (Already compiled expression objects are not
affected.) The argument is an integer which is the OR of several
flag bits. The return value is the previous value of the syntax
flags. Names for the flags are defined in the standard module
`regex_syntax'; read the file `regex_syntax.py' for more
information.
-- exception of module regex: error
Exception raised when a string passed to one of the functions here
is not a valid regular expression (e.g., unmatched parentheses) or
when some other error occurs during compilation or matching. (It
is never an error if a string contains no match for a pattern.)
-- data of module regex: casefold
A string suitable to pass as TRANSLATE argument to `compile' to
map all upper case characters to their lowercase equivalents.
Compiled regular expression objects support these methods:
-- Method on regex: match (STRING, POS)
Return how many characters at the beginning of STRING match the
compiled regular expression. Return `-1' if the string does not
match the pattern (this is different from a zero-length match!).
The optional second parameter POS gives an index in the string
where the search is to start; it defaults to `0'. This is not
completely equivalent to slicing the string; the `'^'' pattern
character matches at the real begin of the string and at positions
just after a newline, not necessarily at the index where the
search is to start.
-- Method on regex: search (STRING, POS)
Return the first position in STRING that matches the regular
expression `pattern'. Return `-1' if no position in the string
matches the pattern (this is different from a zero-length match
anywhere!).
The optional second parameter has the same meaning as for the
`match' method.
-- Method on regex: group (INDEX, INDEX, ...)
This method is only valid when the last call to the `match' or
`search' method found a match. It returns one or more groups of
the match. If there is a single INDEX argument, the result is a
single string; if there are multiple arguments, the result is a
tuple with one item per argument. If the INDEX is zero, the
corresponding return value is the entire matching string; if it
is in the inclusive range [1..9], it is the string matching the
the corresponding parenthesized group (using the default syntax,
groups are parenthesized using `
(' and `
)'). If no such group exists, the corresponding result is `None'.
Compiled regular expressions support these data attributes:
-- attribute of regex: regs
When the last call to the `match' or `search' method found a
match, this is a tuple of pairs of indices corresponding to the
beginning and end of all parenthesized groups in the pattern.
Indices are relative to the string argument passed to `match' or
`search'. The 0-th tuple gives the beginning and end or the
whole pattern. When the last match or search failed, this is
`None'.
-- attribute of regex: last
When the last call to the `match' or `search' method found a
match, this is the string argument passed to that method. When
the last match or search failed, this is `None'.
-- attribute of regex: translate
This is the value of the TRANSLATE argument to `regex.compile'
that created this regular expression object. If the TRANSLATE
argument was omitted in the `regex.compile' call, this is `None'.
File: python-lib.info, Node: marshal, Next: struct, Prev: regex, Up: Built-in Modules
Built-in Module `marshal'
=========================
This module contains functions that can read and write Python values
in a binary format. The format is specific to Python, but independent
of machine architecture issues (e.g., you can write a Python value to
a file on a VAX, transport the file to a Mac, and read it back there).
Details of the format not explained here; read the source if you're
interested.
Not all Python object types are supported; in general, only objects
whose value is independent from a particular invocation of Python can
be written and read by this module. The following types are supported:
`None', integers, long integers, floating point numbers, strings,
tuples, lists, dictionaries, and code objects, where it should be
understood that tuples, lists and dictionaries are only supported as
long as the values contained therein are themselves supported; and
recursive lists and dictionaries should not be written (they will
cause an infinite loop).
There are functions that read/write files as well as functions
operating on strings.
The module defines these functions:
-- function of module marshal: dump (VALUE, FILE)
Write the value on the open file. The value must be a supported
type. The file must be an open file object such as `sys.stdout'
or returned by `open()' or `posix.popen()'.
If the value has an unsupported type, garbage is written which
cannot be read back by `load()'.
-- function of module marshal: load (FILE)
Read one value from the open file and return it. If no valid
value is read, raise `EOFError', `ValueError' or `TypeError'.
The file must be an open file object.
-- function of module marshal: dumps (VALUE)
Return the string that would be written to a file by `dump(value,
file)'. The value must be a supported type.
-- function of module marshal: loads (STRING)
Convert the string to a value. If no valid value is found, raise
`EOFError', `ValueError' or `TypeError'. Extra characters in the
string are ignored.
File: python-lib.info, Node: struct, Next: array, Prev: marshal, Up: Built-in Modules
Built-in module `struct'
========================
This module performs conversions between Python values and C structs
represented as Python strings. It uses "format strings" (explained
below) as a compact descriptions of the lay-out of the C structs and
the intended conversion to/from Python values.
The module defines the following exception and functions:
-- exception of module struct: error
Exception raised on various occasions; argument is a string
describing what is wrong.
-- function of module struct: pack (FMT, V1, V2, ...)
Return a string containing the values `V1, V2, ...' packed
according to the given format. The arguments must match the
values required by the format exactly.
-- function of module struct: unpack (FMT, STRING)
Unpack the string (presumably packed by `pack(FMT, ...)')
according to the given format. The result is a tuple even if it
contains exactly one item. The string must contain exactly the
amount of data required by the format (i.e. `len(STRING)' must
equal `calcsize(FMT)').
-- function of module struct: calcsize (FMT)
Return the size of the struct (and hence of the string)
corresponding to the given format.
Format characters have the following meaning; the conversion between C
and Python values should be obvious given their types:
*Format*
*C* -- *Python*
pad byte -- no value
char -- string of length 1
signed char -- integer
short -- integer
int -- integer
long -- integer
float -- float
double -- float
A format character may be preceded by an integral repeat count; e.g.
the format string `'4h'' means exactly the same as `'hhhh''.
C numbers are represented in the machine's native format and byte
order, and properly aligned by skipping pad bytes if necessary
(according to the rules used by the C compiler).
Examples (all on a big-endian machine):
pack('hhl', 1, 2, 3) == '\000\001\000\002\000\000\000\003'
unpack('hhl', '\000\001\000\002\000\000\000\003') == (1, 2, 3)
calcsize('hhl') == 8
Hint: to align the end of a structure to the alignment requirement of
a particular type, end the format with the code for that type with a
repeat count of zero, e.g. the format `'llh0l'' specifies two pad
bytes at the end, assuming longs are aligned on 4-byte boundaries.
(More format characters are planned, e.g. `'s'' for character arrays,
upper case for unsigned variants, and a way to specify the byte order,
which is useful for [de]constructing network packets and
reading/writing portable binary file formats like TIFF and AIFF.)
File: python-lib.info, Node: array, Prev: struct, Up: Built-in Modules
Built-in module `array'
=======================
This module defines a new object type which can efficiently represent
an array of basic values: characters, integers, floating point
numbers. Arrays are sequence types and behave very much like lists,
except that the type of objects stored in them is constrained. The
type is specified at object creation time by using a "type code",
which is a single character. The following type codes are defined:
*Typecode*
*Type* -- *Minimal size in bytes*
`'c''
character -- 1
`'b''
signed integer -- 1
`'h''
signed integer -- 2
`'l''
signed integer -- 4
`'f''
floating point -- 4
`'d''
floating point -- 8
The actual representation of values is determined by the machine
architecture (strictly spoken, by the C implementation).
The module defines the following function:
-- function of module array: array (TYPECODE, INITIALIZER)
Return a new array whose items are restricted by TYPECODE, and
initialized from the optional INITIALIZER value, which must be a
list or a string. The list or string is passed to the new array's
`fromlist()' or `fromstring()' method (see below) to add initial
items to the array.
Array objects support the following data items and methods:
-- data of module array: typecode
The typecode character used to create the array.
-- data of module array: itemsize
The length in bytes of one array item in the internal
representation.
-- function of module array: append (X)
Append a new item with value X to the end of the array.
-- function of module array: insert (I, X)
Insert a new item with value X in the array before position I.
-- function of module array: read (F, N)
Read N items (as machine values) from the file object F and
append them to the end of the array. If less than N items are
available, `EOFError' is raised, but the items that were
available are still inserted into the array.
-- function of module array: write (F)
Write all items (as machine values) to the file object F.
-- function of module array: fromstring (S)
Appends items from the string, interpreting the string as an
array of machine values (i.e. as if it had been read from a file
using the `read()' method).
-- function of module array: tostring ()
Convert the array to an array of machine values and return the
string representation (the same sequence of bytes that would be
written to a file by the `write()' method.)
-- function of module array: fromlist (LIST)
Appends items from the list. This is equivalent to `for x in
LIST: a.append(x)' except that if there is a type error, the
array is unchanged.
-- function of module array: tolist ()
Convert the array to an ordinary list with the same items.
When an array object is printed or converted to a string, it is
represented as `array(TYPECODE, INITIALIZER)'. The INITIALIZER is
omitted if the array is empty, otherwise it is a string if the
TYPECODE is `'c'', otherwise it is a list of numbers. The string is
guaranteed to be able to be converted back to an array with the same
type and value using reverse quotes (```'). Examples:
array('l')
array('c', 'hello world')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
File: python-lib.info, Node: Standard Modules, Next: MOST OPERATING SYSTEMS, Prev: Built-in Modules, Up: Top
Standard Modules
****************
The following standard modules are defined. They are available in one
of the directories in the default module search path (try printing
`sys.path' to find out the default search path.)
* Menu:
* string:: Standard Module `string'
* rand:: Standard Module `rand'
* whrandom:: Standard Module `whrandom'
* regsub:: Standard Module `regsub'
* os:: Standard Module `os'
File: python-lib.info, Node: string, Next: rand, Up: Standard Modules
Standard Module `string'
========================
This module defines some constants useful for checking character
classes, some exceptions, and some useful string functions. The
constants are:
-- data of module string: digits
The string `'0123456789''.
-- data of module string: hexdigits
The string `'0123456789abcdefABCDEF''.
-- data of module string: letters
The concatenation of the strings `lowercase' and `uppercase'
described below.
-- data of module string: lowercase
The string `'abcdefghijklmnopqrstuvwxyz''.
-- data of module string: octdigits
The string `'01234567''.
-- data of module string: uppercase
The string `'ABCDEFGHIJKLMNOPQRSTUVWXYZ''.
-- data of module string: whitespace
A string containing all characters that are considered whitespace,
i.e., space, tab and newline. This definition is used by
`split()' and `strip()'.
The exceptions are:
-- exception of module string: atoi_error
Exception raised by `atoi' when a non-numeric string argument is
detected. The exception argument is the offending string.
-- exception of module string: index_error
Exception raised by `index' when SUB is not found. The argument
are the offending arguments to index: `(S, SUB)'.
The functions are:
-- function of module string: atoi (S)
Converts a string to a number. The string must consist of one or
more digits, optionally preceded by a sign (`+' or `-').
-- function of module string: expandtabs (S, TABSIZE)
Expand tabs in a string, i.e. replace them by one or more spaces,
depending on the current column and the given tab size. The
column number is reset to zero after each newline occurring in
the string. This doesn't understand other non-printing
characters or escape sequences.
-- function of module string: find (S, SUB, I)
Return the lowest index in S not smaller than I where the
substring SUB is found. Return `-1' when SUB does not occur as a
substring of S with index at least I. If I is omitted, it
defaults to `0'.
-- function of module string: index (S, SUB, I)
Like `index' but raise `index_error' when the substring is not
found.
-- function of module string: lower (S)
Convert letters to lower case.
-- function of module string: split (S)
Returns a list of the whitespace-delimited words of the string S.
-- function of module string: splitfields (S, SEP)
Returns a list containing the fields of the string S, using the
string SEP as a separator. The list will have one more items
than the number of non-overlapping occurrences of the separator
in the string. Thus, `string.splitfields(S, ' ')' is not the
same as `string.split(S)', as the latter only returns non-empty
words. As a special case, `splitfields(S, '')' returns `[S]',
for any string S. (See also `regsub.split()'.)
-- function of module string: join (WORDS)
Concatenate a list or tuple of words with intervening spaces.
-- function of module string: joinfields (WORDS, SEP)
Concatenate a list or tuple of words with intervening separators.
It is always true that `string.joinfields(string.splitfields(T,
SEP), SEP)' equals T.
-- function of module string: strip (S)
Removes leading and trailing whitespace from the string S.
-- function of module string: swapcase (S)
Converts lower case letters to upper case and vice versa.
-- function of module string: upper (S)
Convert letters to upper case.
-- function of module string: ljust (S, WIDTH)
-- function of module string: rjust (S, WIDTH)
-- function of module string: center (S, WIDTH)
These functions respectively left-justify, right-justify and
center a string in a field of given width. They return a string
that is at least WIDTH characters wide, created by padding the
string S with spaces until the given width on the right, left or
both sides. The string is never truncated.
-- function of module string: zfill (S, WIDTH)
Pad a numeric string on the left with zero digits until the given
width is reached. Strings starting with a sign are handled
correctly.
File: python-lib.info, Node: rand, Next: whrandom, Prev: string, Up: Standard Modules
Standard Module `rand'
======================
This module implements a pseudo-random number generator with an
interface similar to `rand()' in C. It defines the following
functions:
-- function of module rand: rand ()
Returns an integer random number in the range [0 ... 32768).
-- function of module rand: choice (S)
Returns a random element from the sequence (string, tuple or list)
S.
-- function of module rand: srand (SEED)
Initializes the random number generator with the given integral
seed. When the module is first imported, the random number is
initialized with the current time.
File: python-lib.info, Node: whrandom, Next: regsub, Prev: rand, Up: Standard Modules
Standard Module `whrandom'
==========================
This module implements a Wichmann-Hill pseudo-random number generator.
It defines the following functions:
-- function of module whrandom: random ()
Returns the next random floating point number in the range [0.0
... 1.0).
-- function of module whrandom: seed (X, Y, Z)
Initializes the random number generator from the integers X, Y and
Z. When the module is first imported, the random number is
initialized using values derived from the current time.
File: python-lib.info, Node: regsub, Next: os, Prev: whrandom, Up: Standard Modules
Standard Module `regsub'
========================
This module defines a number of functions useful for working with
regular expressions (see built-in module `regex').
-- function of module regsub: sub (PAT, REPL, STR)
Replace the first occurrence of pattern PAT in string STR by
replacement REPL. If the pattern isn't found, the string is
returned unchanged. The pattern may be a string or an already
compiled pattern. The replacement may contain references
`\DIGIT' to subpatterns and escaped backslashes.
-- function of module regsub: gsub (PAT, REPL, STR)
Replace all (non-overlapping) occurrences of pattern PAT in
string STR by replacement REPL. The same rules as for `sub()'
apply. Empty matches for the pattern are replaced only when not
adjacent to a previous match, so e.g. `gsub('', '-', 'abc')'
returns `'-a-b-c-''.
-- function of module regsub: split (STR, PAT)
Split the string STR in fields separated by delimiters matching
the pattern PAT, and return a list containing the fields. Only
non-empty matches for the pattern are considered, so e.g.
`split('a:b', ':*')' returns `['a', 'b']' and `split('abc', '')'
returns `['abc']'.
File: python-lib.info, Node: os, Prev: regsub, Up: Standard Modules
Standard Module `os'
====================
This module provides a more portable way of using operating system
(OS) dependent functionality than importing an OS dependent built-in
module like `posix'.
When the optional built-in module `posix' is available, this module
exports the same functions and data as `posix'; otherwise, it searches
for an OS dependent built-in module like `mac' and exports the same
functions and data as found there. The design of all Python's
built-in OS dependen modules is such that as long as the same
functionality is available, it uses the same interface; e.g., the
function `os.stat(FILE)' returns stat info about a FILE in a format
compatible with the POSIX interface.
Extensions peculiar to a particular OS are also available through the
`os' module, but using them is of course a threat to portability!
Note that after the first time `os' is imported, there is *no*
performance penalty in using functions from `os' instead of directly
from the OS dependent built-in module, so there should be *no* reason
not to use `os'!
In addition to whatever the correct OS dependent module exports, the
following variables are always exported by `os':
-- data of module os: name
The name of the OS dependent module imported, e.g. `'posix'' or
`'mac''.
-- data of module os: path
The corresponding OS dependent standard module for pathname
operations, e.g., `posixpath' or `macpath'. Thus, (given the
proper imports), `os.path.split(FILE)' is equivalent to but more
portable than `posixpath.split(FILE)'.
-- data of module os: curdir
The constant string used by the OS to refer to the current
directory, e.g. `'.'' for POSIX or `':'' for the Mac.
-- data of module os: pardir
The constant string used by the OS to refer to the parent
directory, e.g. `'..'' for POSIX or `'::'' for the Mac.
-- data of module os: sep
The character used by the OS to separate pathname components, e.g.
`'/'' for POSIX or `':'' for the Mac. Note that knowing this is
not sufficient to be able to parse or concatenate
pathnames--better use `os.path.split()' and `os.path.join()'--but
it is occasionally useful.
File: python-lib.info, Node: MOST OPERATING SYSTEMS, Next: UNIX ONLY, Prev: Standard Modules, Up: Top
MOST OPERATING SYSTEMS
**********************
* Menu:
* posix:: Built-in Module `posix'
* posixpath:: Standard Module `posixpath'
* getopt:: Standard Module `getopt'
File: python-lib.info, Node: posix, Next: posixpath, Up: MOST OPERATING SYSTEMS
Built-in Module `posix'
=======================
This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly
diguised UNIX interface). It is available in all Python versions
except on the Macintosh; the MS-DOS version does not support certain
functions. The descriptions below are very terse; refer to the
corresponding UNIX manual entry for more information.
Errors are reported as exceptions; the usual exceptions are given for
type errors, while errors reported by the system calls raise
`posix.error', described below.
Module `posix' defines the following data items:
-- data of module posix: environ
A dictionary representing the string environment at the time the
interpreter was started. (Modifying this dictionary does not
affect the string environment of the interpreter.) For example,
`posix.environ['HOME']' is the pathname of your home directory,
equivalent to `getenv("HOME")' in C.
-- exception of module posix: error
This exception is raised when an POSIX function returns a
POSIX-related error (e.g., not for illegal argument types). Its
string value is `'posix.error''. The accompanying value is a
pair containing the numeric error code from `errno' and the
corresponding string, as would be printed by the C function
`perror()'.
It defines the following functions:
-- function of module posix: chdir (PATH)
Change the current working directory to PATH.
-- function of module posix: chmod (PATH, MODE)
Change the mode of PATH to the numeric MODE.
-- function of module posix: close (FD)
Close file descriptor FD.
-- function of module posix: dup (FD)
Return a duplicate of file descriptor FD.
-- function of module posix: dup2 (FD, FD2)
Duplicate file descriptor FD to FD2, closing the latter first if
necessary. Return `None'.
-- function of module posix: _exit (N)
Exit to the system with status N, without calling cleanup
handlers, flushing stdio buffers, etc. (Not on MS-DOS.)
Note: the standard way to exit is `sys.exit(N)'. `posix.exit()'
should normally only be used in the child process after a
`fork()'.
-- function of module posix: exec (PATH, ARGS)
Execute the executable PATH with argument list ARGS, replacing
the current process (i.e., the Python interpreter). The argument
list may be a tuple or list of strings. (Not on MS-DOS.)
-- function of module posix: fork ()
Fork a child process. Return 0 in the child, the child's process
id in the parent. (Not on MS-DOS.)
-- function of module posix: fstat (FD)
Return status for file descriptor FD, like `stat()'.
-- function of module posix: getcwd ()
Return a string representing the current working directory.
-- function of module posix: getegid ()
Return the current process's effective group id. (Not on MS-DOS.)
-- function of module posix: geteuid ()
Return the current process's effective user id. (Not on MS-DOS.)
-- function of module posix: getgid ()
Return the current process's group id. (Not on MS-DOS.)
-- function of module posix: getpid ()
Return the current process id. (Not on MS-DOS.)
-- function of module posix: getppid ()
Return the parent's process id. (Not on MS-DOS.)
-- function of module posix: getuid ()
Return the current process's user id. (Not on MS-DOS.)
-- function of module posix: kill (PID, SIG)
Kill the process PID with signal SIG. (Not on MS-DOS.)
-- function of module posix: link (SRC, DST)
Create a hard link pointing to SRC named DST. (Not on MS-DOS.)
-- function of module posix: listdir (PATH)
Return a list containing the names of the entries in the
directory. The list is in arbitrary order. It includes the
special entries `'.'' and `'..'' if they are present in the
directory.
-- function of module posix: lseek (FD, POS, HOW)
Set the current position of file descriptor FD to position POS,
modified by HOW: 0 to set the position relative to the beginning
of the file; 1 to set it relative to the current position; 2 to
set it relative to the end of the file.
-- function of module posix: lstat (PATH)
Like `stat()', but do not follow symbolic links. (On systems
without symbolic links, this is identical to `posix.stat'.)
-- function of module posix: mkdir (PATH, MODE)
Create a directory named PATH with numeric mode MODE.
-- function of module posix: nice (INCREMENT)
Add INCR to the process' "niceness". Return the new niceness.
(Not on MS-DOS.)
-- function of module posix: open (FILE, FLAGS, MODE)
Open the file FILE and set various flags according to FLAGS and
possibly its mode according to MODE. Return the file descriptor
for the newly opened file.
-- function of module posix: pipe ()
Create a pipe. Return a pair of file descriptors `(r, w)' usable
for reading and writing, respectively. (Not on MS-DOS.)
-- function of module posix: popen (COMMAND, MODE)
Open a pipe to or from COMMAND. The return value is an open file
object connected to the pipe, which can be read or written
depending on whether MODE is `'r'' or `'w''. (Not on MS-DOS.)
-- function of module posix: read (FD, N)
Read at most N bytes from file descriptor FD. Return a string
containing the bytes read.
-- function of module posix: readlink (PATH)
Return a string representing the path to which the symbolic link
points. (On systems without symbolic links, this always raises
`posix.error'.)
-- function of module posix: rename (SRC, DST)
Rename the file or directory SRC to DST.
-- function of module posix: rmdir (PATH)
Remove the directory PATH.
-- function of module posix: stat (PATH)
Perform a *stat* system call on the given path. The return value
is a tuple of at least 10 integers giving the most important (and
portable) members of the *stat* structure, in the order `st_mode',
`st_ino', `st_dev', `st_nlink', `st_uid', `st_gid', `st_size',
`st_atime', `st_mtime', `st_ctime'. More items may be added at
the end by some implementations. (On MS-DOS, some items are
filled with dummy values.)
Note: The standard module `stat' defines functions and constants
that are useful for extracting information from a stat structure.
-- function of module posix: symlink (SRC, DST)
Create a symbolic link pointing to SRC named DST. (On systems
without symbolic links, this always raises `posix.error'.)
-- function of module posix: system (COMMAND)
Execute the command (a string) in a subshell. This is
implemented by calling the Standard C function `system()', and
has the same limitations. Changes to `posix.environ',
`sys.stdin' etc. are not reflected in the environment of the
executed command. The return value is the exit status of the
process as returned by Standard C `system()'.
-- function of module posix: times ()
Return a 4-tuple of floating point numbers indicating accumulated
CPU times, in seconds. The items are: user time, system time,
children's user time, and children's system time, in that order.
See the UNIX manual page times(2). (Not on MS-DOS.)
-- function of module posix: umask (MASK)
Set the current numeric umask and returns the previous umask.
(Not on MS-DOS.)
-- function of module posix: uname ()
Return a 5-tuple containing information identifying the current
operating system. The tuple contains 5 strings: `(SYSNAME,
NODENAME, RELEASE, VERSION, MACHINE)'. Some systems truncate the
nodename to 8 characters or to the leading component; an better
way to get the hostname is `socket.gethostname()'. (Not on
MS-DOS, nor on older UNIX systems.)
-- function of module posix: unlink (PATH)
Unlink PATH.
-- function of module posix: utime (PATH, (ATIME, MTIME))
Set the access and modified time of the file to the given values.
(The second argument is a tuple of two items.)
-- function of module posix: wait ()
Wait for completion of a child process, and return a tuple
containing its pid and exit status indication (encoded as by
UNIX). (Not on MS-DOS.)
-- function of module posix: waitpid (PID, OPTIONS)
Wait for completion of a child process given by proces id, and
return a tuple containing its pid and exit status indication
(encoded as by UNIX). The semantics of the call are affected by
the value of the integer options, which should be 0 for normal
operation. (If the system does not support waitpid(), this
always raises `posix.error'. Not on MS-DOS.)
-- function of module posix: write (FD, STR)
Write the string STR to file descriptor fd. Return the number of
bytes actually written.
File: python-lib.info, Node: posixpath, Next: getopt, Prev: posix, Up: MOST OPERATING SYSTEMS
Standard Module `posixpath'
===========================
This module implements some useful functions on POSIX pathnames.
-- function of module posixpath: basename (P)
Return the base name of pathname P. This is the second half of
the pair returned by `posixpath.split(P)'.
-- function of module posixpath: commonprefix (LIST)
Return the longest string that is a prefix of all strings in LIST.
If LIST is empty, return the empty string (`''').
-- function of module posixpath: exists (P)
Return true if P refers to an existing path.
-- function of module posixpath: expanduser (P)
Return the argument with an initial component of `~' or `~USER'
replaced by that USER's home directory. An initial `~' is
replaced by the environment variable `$HOME'; an initial `~USER'
is looked up in the password directory through the built-in
module `pwd'. If the expansion fails, or if the path does not
begin with a tilde, the path is returned unchanged.
-- function of module posixpath: isabs (P)
Return true if P is an absolute pathname (begins with a slash).
-- function of module posixpath: isfile (P)
Return true if P is an existing regular file. This follows
symbolic links, so both islink() and isfile() can be true for the
same path.
-- function of module posixpath: isdir (P)
Return true if P is an existing directory. This follows symbolic
links, so both islink() and isdir() can be true for the same path.
-- function of module posixpath: islink (P)
Return true if P refers to a directory entry that is a symbolic
link. Always false if symbolic links are not supported.
-- function of module posixpath: ismount (P)
Return true if P is a mount point. (This currently checks whether
`P/..' is on a different device as P or whether `P/..' and P
point to the same i-node on the same device -- is this test
correct for all UNIX and POSIX variants?)
-- function of module posixpath: join (P, Q)
Join the paths P and Q intelligently: If Q is an absolute path,
the return value is Q. Otherwise, the concatenation of P and Q
is returned, with a slash (`'/'') inserted unless P is empty or
ends in a slash.
-- function of module posixpath: normcase (P)
Normalize the case of a pathname. This returns the path
unchanged; however, a similar function in `macpath' converts
upper case to lower case.
-- function of module posixpath: samefile (P, Q)
Return true if both pathname arguments refer to the same file or
directory (as indicated by device number and i-node number).
Raise an exception if a stat call on either pathname fails.
-- function of module posixpath: split (P)
Split the pathname P in a pair `(HEAD, TAIL)', where TAIL is the
last pathname component and HEAD is everything leading up to
that. If P ends in a slash (except if it is the root), the
trailing slash is removed and the operation applied to the
result; otherwise, `join(HEAD, TAIL)' equals P. The TAIL part
never contains a slash. Some boundary cases: if P is the root,
HEAD equals P and TAIL is empty; if P is empty, both HEAD and
TAIL are empty; if P contains no slash, HEAD is empty and TAIL
equals P.
-- function of module posixpath: splitext (P)
Split the pathname P in a pair `(ROOT, EXT)' such that `ROOT +
EXT == P', the last component of ROOT contains no periods, and
EXT is empty or begins with a period.
-- function of module posixpath: walk (P, VISIT, ARG)
Calls the function VISIT with arguments `(ARG, DIRNAME, NAMES)'
for each directory in the directory tree rooted at P (including P
itself, if it is a directory). The argument DIRNAME specifies
the visited directory, the argument NAMES lists the files in the
directory (gotten from `posix.listdir(DIRNAME)'). The VISIT
function may modify NAMES to influence the set of directories
visited below DIRNAME, e.g., to avoid visiting certain parts of
the tree. (The object referred to by NAMES must be modified in
place, using `del' or slice assignment.)
File: python-lib.info, Node: getopt, Prev: posixpath, Up: MOST OPERATING SYSTEMS
Standard Module `getopt'
========================
This module helps scripts to parse the command line arguments in
`sys.argv'. It uses the same conventions as the UNIX `getopt()'
function. It defines the function `getopt.getopt(args, options)' and
the exception `getopt.error'.
The first argument to `getopt()' is the argument list passed to the
script with its first element chopped off (i.e., `sys.argv[1:]'). The
second argument is the string of option letters that the script wants
to recognize, with options that require an argument followed by a
colon (i.e., the same format that UNIX `getopt()' uses). The return
value consists of two elements: the first is a list of
option-and-value pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice of
the first argument). Each option-and-value pair returned has the
option as its first element, prefixed with a hyphen (e.g., `'-x''),
and the option argument as its second element, or an empty string if
the option has no argument. The options occur in the list in the same
order in which they were found, thus allowing multiple occurrences.
Example:
>>> import getopt, string
>>> args = string.split('-a -b -cfoo -d bar a1 a2')
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
>>>
The exception `getopt.error = 'getopt error'' is raised when an
unrecognized option is found in the argument list or when an option
requiring an argument is given none. The argument to the exception is
a string indicating the cause of the error.
File: python-lib.info, Node: UNIX ONLY, Next: AMOEBA ONLY, Prev: MOST OPERATING SYSTEMS, Up: Top
UNIX ONLY
*********
* Menu:
* pwd:: Built-in Module `pwd'
* grp:: Built-in Module `grp'
* socket:: Built-in Module `socket'
* select:: Built-in module `select'
* dbm:: Built-in Module `dbm'
* thread:: Built-in Module `thread'
File: python-lib.info, Node: pwd, Next: grp, Up: UNIX ONLY
Built-in Module `pwd'
=====================
This module provides access to the UNIX password database. It is
available on all UNIX versions.
Password database entries are reported as 7-tuples containing the
following items from the password database (see `<pwd.h>'), in order:
`pw_name', `pw_passwd', `pw_uid', `pw_gid', `pw_gecos', `pw_dir',
`pw_shell'. The uid and gid items are integers, all others are
strings. An exception is raised if the entry asked for cannot be
found.
It defines the following items:
-- function of module pwd: getpwuid (UID)
Return the password database entry for the given numeric user ID.
-- function of module pwd: getpwnam (NAME)
Return the password database entry for the given user name.
-- function of module pwd: getpwall ()
Return a list of all available password database entries, in
arbitrary order.
File: python-lib.info, Node: grp, Next: socket, Prev: pwd, Up: UNIX ONLY
Built-in Module `grp'
=====================
This module provides access to the UNIX group database. It is
available on all UNIX versions.
Group database entries are reported as 4-tuples containing the
following items from the group database (see `<grp.h>'), in order:
`gr_name', `gr_passwd', `gr_gid', `gr_mem'. The gid is an integer,
name and password are strings, and the member list is a list of
strings. (Note that most users are not explicitly listed as members
of the group(s) they are in.) An exception is raised if the entry
asked for cannot be found.
It defines the following items:
-- function of module grp: getgrgid (GID)
Return the group database entry for the given numeric group ID.
-- function of module grp: getgrnam (NAME)
Return the group database entry for the given group name.
-- function of module grp: getgrall ()
Return a list of all available group entries entries, in
arbitrary order.